package com.mfn.sportjava.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MyBatis-Plus 配置类
 * @author Anyang
 * @version 1.0.0
 * @date 2025/05/18
 */
@Configuration
public class MyBatisPlusConfig {

    private static final Logger log = LoggerFactory.getLogger(MyBatisPlusConfig.class);

    /**
     * MyBatis-Plus 拦截器配置
     * 分页插件。
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        // 分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mybatisPlusInterceptor;
    }

    /**
     * 自动填充处理器，用于处理 createdAt 和 updatedAt 字段。
     */
    @Component
    public static class MyMetaObjectHandler implements MetaObjectHandler {
        private static final Logger log = LoggerFactory.getLogger(MyMetaObjectHandler.class);

        @Override
        public void insertFill(MetaObject metaObject) {
            log.debug("MyBatis-Plus MetaObjectHandler: Start insert fill ....");
            // 严格模式填充，如果属性不存在或已手动设置则不覆盖
            this.strictInsertFill(metaObject, "createdAt", LocalDateTime::now, LocalDateTime.class);
            this.strictInsertFill(metaObject, "updatedAt", LocalDateTime::now, LocalDateTime.class);
            // 普通模式填充，会覆盖手动设置的值
            // this.setFieldValByName("createdAt", LocalDateTime.now(), metaObject);
            // this.setFieldValByName("updatedAt", LocalDateTime.now(), metaObject);
        }

        @Override
        public void updateFill(MetaObject metaObject) {
            log.debug("MyBatis-Plus MetaObjectHandler: Start update fill ....");
            this.strictUpdateFill(metaObject, "updatedAt", LocalDateTime::now, LocalDateTime.class);
            // this.setFieldValByName("updatedAt", LocalDateTime.now(), metaObject);
        }
    }
}